package util;

import org.apache.ibatis.jdbc.SQL;

public class SQLBuilder {

    /**
     * mybatis SQL 语句构建器
     */
    public static void main(String[] args) {

        String selectPersonSql = new SQL() {
            {
                SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
                SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
                FROM("PERSON P");
                FROM("ACCOUNT A");
                INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
                INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
                WHERE("P.ID = A.ID");
                WHERE("P.FIRST_NAME like ?");
                OR();
                WHERE("P.LAST_NAME like ?");
                GROUP_BY("P.ID");
                HAVING("P.LAST_NAME like ?");
            }
        }.toString();

        System.out.println("查询语句 " + selectPersonSql);

        selectPersonSql = selectPersonLike("5", "c", "l");

        String insertSql = insertPersonSql();
        System.out.println("插入语句 " + insertSql);

        String deleteSql = new SQL() {
            {
                DELETE_FROM("PERSON");
                WHERE("ID = #{id}");
            }
        }.toString();
        System.out.println("删除语句 " + deleteSql);
    }

    // Builder / Fluent 风格
    public static String insertPersonSql() {
        String sql = new SQL().INSERT_INTO("PERSON").VALUES("ID, FIRST_NAME", "#{id}, #{firstName}")
                .VALUES("LAST_NAME", "#{lastName}").toString();
        return sql;
    }

    // 动态条件（注意参数需要使用 final 修饰，以便匿名内部类对它们进行访问）
    public static String selectPersonLike(final String id, final String firstName, final String lastName) {
        return new SQL() {
            {
                SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");
                FROM("PERSON P");
                if (id != null) {
                    WHERE("P.ID like #{id}");
                }
                if (firstName != null) {
                    WHERE("P.FIRST_NAME like #{firstName}");
                }
                if (lastName != null) {
                    WHERE("P.LAST_NAME like #{lastName}");
                }
                ORDER_BY("P.LAST_NAME");
            }
        }.toString();
    }

}
